import { get } from '../http'
import model from '../../model'

async function getDataTypes(mode) {
  if (mode === 'frontend') {
    return { ok: true, data: sortDataTypes(model.dataTypes ?? []) }
  } else {
    try {
      const resp = await get('/dataTypes')
      if (resp.ok) {
        return { ok: true, data: sortDataTypes(resp.data ?? []) }
      } else {
        return { ok: false, message: resp.message }
      }
    } catch (error) {
      return { ok: false, message: error.message }
    }
  }
}

function sortDataTypes(values) {
  const data = new Set(values)
  const list = []
  for (const item of ['Hex', 'UTF-8', 'Int', 'Long', 'Float', 'Double', 'Boolean', 'Short']) {
    if (data.has(item)) {
      list.push(item)
    }
  }
  const set = new Set(list)
  for (const item of data) {
    if (!set.has(item)) {
      list.push(item)
    }
  }
  return list
}

export default {
  getDataTypes
}